// 修改信息页面组件

import './index.less';
import {Image, Picker, Text, View} from "@tarojs/components";
import {utils} from "../../utils/utils";
import Taro from "@tarojs/taro";
import {Api} from "../../api/api";
import {wxActions} from "../../utils/wxActions";

export function AvatarRow(props) {
    const {avatarUrl, dispatch} = props;

    const chooseAvatar = () => {
        Taro.chooseImage({
            success: function (res) {
                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                let tempFilePath = res.tempFilePaths[0];
                Api.uploadAvatar({
                    avatarfile: tempFilePath
                }).then(res => {
                   wxActions.refreshUserInfo(dispatch)
                }).catch((err) => {
                    wxActions.showTip(err.message);
                });
            }
        })
    }

    return (
        <View className={"avatarRow"}>
            <View className={"avatarRow_title"}>
                <Text>头像</Text>
            </View>
            <View className={"avatarRow_img"} onClick={chooseAvatar}>
                <Image src={avatarUrl} mode={"aspectFill"}/>
            </View>
        </View>
    )
}

export function Divider(props) {

    return (
        <View className={"divider"}>

        </View>
    )
}

export function FormItem(props) {
    const {title, value, placeholder, handleClick, isSelect, setValue} = props;

    const renderValue = () => {
        if (utils.isEmpty(value)) {
            return (
                <View className={utils.classNames("renderValue", "placeholder")} onClick={handleClick}>
                    <Text>{placeholder}</Text>
                </View>
            )
        } else {
            return (
                <View className={utils.classNames("renderValue", "value")} onClick={handleClick}>
                    <Text>{value}</Text>
                </View>
            )
        }
    }

    const handleSelect = (e) => {
        setValue(e.detail.value.join(" "));
    }

    return (
        <View className={"formItem"}>
            <View className={"title"}>
                <Text>{title}</Text>
            </View>
            {
                isSelect ?
                    <Picker mode='region' onChange={handleSelect}>
                        {renderValue()}
                    </Picker>
                    :
                    renderValue()
            }
            <View className={"formItem_divider"}/>
        </View>
    )
}
